/*
 * CAD System for seamlessly constructing 2D and 3D scenes with aspects and motion
 * Copyright (C) 2013 Bernhard Haumacher and others
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.haumacher.draw5d.dataflow.core;

import java.util.List;

import de.haumacher.draw5d.dataflow.Block;
import de.haumacher.draw5d.dataflow.Observable;
import de.haumacher.draw5d.dataflow.Options;
import de.haumacher.draw5d.dataflow.Property;

/**
 * Base class for handling generic access to all parameter dependencies.
 * 
 * @author <a href="mailto:haui@haumacher.de">Bernhard Haumacher</a>
 * @version $Revision: 30 $ $Author: haumacher@googlemail.com $ $Date: 2013-11-08 20:37:25 +0000 (Fri, 08 Nov 2013) $
 */
public class InputImpl extends DependencyContainer implements Options {

	private final OptionsImpl _data;

	/**
	 * Creates a {@link InputImpl}.
	 * 
	 * @param owner
	 *        The {@link Observable} this is the parameter holder for. This holder depends on the
	 *        contents of this parameter object.
	 * @param properties
	 *        See {@link #getProperties()}.
	 */
	public InputImpl(Observable owner, Property<? extends Observable>... properties) {
		super(owner);
		_data = new OptionsImpl(properties);
	}

	@Override
	public List<Property<? extends Observable>> getProperties() {
		return _data.getProperties();
	}

	@Override
	public <T extends Observable> T get(Property<T> property) {
		return _data.get(property);
	}

	@Override
	public <T extends Observable> T set(Property<T> property, T newValue) {
		T oldValue = _data.set(property, newValue);
		if (newValue == oldValue) {
			return oldValue;
		}

		if (oldValue != null) {
			unregisterUsage(oldValue);
		}
		if (newValue != null) {
			registerUsage(newValue);
		}
		invalidate();

		return oldValue;
	}

	@Override
	public void foreachDependency(Block<? super Observable> block) {
		for (Property<? extends Observable> property : _data.getProperties()) {
			Observable parameter = _data.get(property);
			if (parameter == null) {
				continue;
			}

			block.apply(parameter);
		}

		super.foreachDependency(block);
	}

}
